package cn.regexp.seckill.mq;

import cn.regexp.seckill.service.IOrderInfoService;
import cn.regexp.seckill.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author Regexpei
 * @date 2024/7/5 23:55
 * @description 秒杀预处理监听器
 */
@Component
@RocketMQMessageListener(consumerGroup = "MQOrderPendingTopicListener", topic = MQConstant.ORDER_PEDDING_TOPIC)
@Slf4j
public class MQOrderPendingTopicListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("进入消费者消费消息方法...");
        // 从订单消息对象中获取信息
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        Long userPhone = orderMessage.getUserPhone();
        // 创建订单消息结果对象
        OrderMQResult orderMQResult = new OrderMQResult();
        BeanUtils.copyProperties(orderMessage, orderMQResult);

        String tag;
        try {
            // 调用业务层秒杀方法
            String orderNo = orderInfoService.doSeckill(time, seckillId, userPhone);
            // 将订单编号封装到对象中
            orderMQResult.setOrderNo(orderNo);
            // 成功标签
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;

            // 创建 Message 对象
            Message<OrderMQResult> message = MessageBuilder.withPayload(orderMQResult).build();
            // 发送延时消息，根据用户是否支付进行其它业务逻辑
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, message, 5000,
                    MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);

            log.info("MQOrderPendingTopicListener#onMessage --> 秒杀成功");
        } catch (Exception e) {
            log.error("秒杀失败，message: {}", e.getMessage());
            // 进入到这里，说明秒杀失败，需要将错误状态码和错误提示信息返回给前端
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            // 失败标签
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;

            log.info("MQOrderPendingTopicListener#onMessage --> 秒杀失败");
        }
        // 发送请求消息
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC + ":" + tag, orderMQResult);
    }
}
